package com.example.handheld4_gsignal_app.network;

import android.content.Context;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.JsonObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * API客户端 - 处理HTTP请求
 */
public class ApiClient {
    
    private static final String TAG = "ApiClient";
    private static final String BASE_URL = "http://101.201.68.169:8886"; // 服务器地址
    private static final int CONNECT_TIMEOUT = 10000; // 连接超时时间
    private static final int READ_TIMEOUT = 30000; // 读取超时时间
    
    private Context context;
    private Gson gson;
    private ExecutorService executorService;
    private static ApiClient instance;
    
    public ApiClient() {
        this.gson = new Gson();
        this.executorService = Executors.newFixedThreadPool(4);
    }
    
    public ApiClient(Context context) {
        this.context = context;
        this.gson = new Gson();
        this.executorService = Executors.newFixedThreadPool(4);
    }
    
    /**
     * 获取单例实例
     */
    public static ApiClient getInstance(Context context) {
        if (instance == null) {
            instance = new ApiClient(context);
        }
        return instance;
    }
    
    /**
     * API回调接口
     */
    public interface ApiCallback {
        void onSuccess(String response);
        void onError(String error);
    }
    
    /**
     * GET请求
     */
    public void get(String endpoint, ApiCallback callback) {
        executorService.execute(() -> {
            try {
                String url = BASE_URL + endpoint;
                Log.d(TAG, "GET请求: " + url);
                
                HttpURLConnection connection = createConnection(url, "GET");
                connection.connect();
                
                int responseCode = connection.getResponseCode();
                String response = readResponse(connection);
                
                if (responseCode >= 200 && responseCode < 300) {
                    Log.d(TAG, "GET请求成功: " + responseCode);
                    callback.onSuccess(response);
                } else {
                    Log.e(TAG, "GET请求失败: " + responseCode + ", " + response);
                    callback.onError("请求失败: " + responseCode + " - " + response);
                }
                
                connection.disconnect();
                
            } catch (Exception e) {
                Log.e(TAG, "GET请求异常", e);
                callback.onError("请求异常: " + e.getMessage());
            }
        });
    }
    
    /**
     * POST请求
     */
    public void post(String endpoint, String requestBody, ApiCallback callback) {
        executorService.execute(() -> {
            try {
                String url = BASE_URL + endpoint;
                Log.d(TAG, "POST请求: " + url);
                Log.d(TAG, "请求体: " + requestBody);
                
                HttpURLConnection connection = createConnection(url, "POST");
                connection.setDoOutput(true);
                
                // 写入请求体
                try (OutputStream os = connection.getOutputStream()) {
                    byte[] input = requestBody.getBytes(StandardCharsets.UTF_8);
                    os.write(input, 0, input.length);
                }
                
                connection.connect();
                
                int responseCode = connection.getResponseCode();
                String response = readResponse(connection);
                
                if (responseCode >= 200 && responseCode < 300) {
                    Log.d(TAG, "POST请求成功: " + responseCode);
                    callback.onSuccess(response);
                } else {
                    Log.e(TAG, "POST请求失败: " + responseCode + ", " + response);
                    callback.onError("请求失败: " + responseCode + " - " + response);
                }
                
                connection.disconnect();
                
            } catch (Exception e) {
                Log.e(TAG, "POST请求异常", e);
                callback.onError("请求异常: " + e.getMessage());
            }
        });
    }
    
    /**
     * PUT请求
     */
    public void put(String endpoint, String requestBody, ApiCallback callback) {
        executorService.execute(() -> {
            try {
                String url = BASE_URL + endpoint;
                Log.d(TAG, "PUT请求: " + url);
                Log.d(TAG, "请求体: " + requestBody);
                
                HttpURLConnection connection = createConnection(url, "PUT");
                connection.setDoOutput(true);
                
                // 写入请求体
                try (OutputStream os = connection.getOutputStream()) {
                    byte[] input = requestBody.getBytes(StandardCharsets.UTF_8);
                    os.write(input, 0, input.length);
                }
                
                connection.connect();
                
                int responseCode = connection.getResponseCode();
                String response = readResponse(connection);
                
                if (responseCode >= 200 && responseCode < 300) {
                    Log.d(TAG, "PUT请求成功: " + responseCode);
                    callback.onSuccess(response);
                } else {
                    Log.e(TAG, "PUT请求失败: " + responseCode + ", " + response);
                    callback.onError("请求失败: " + responseCode + " - " + response);
                }
                
                connection.disconnect();
                
            } catch (Exception e) {
                Log.e(TAG, "PUT请求异常", e);
                callback.onError("请求异常: " + e.getMessage());
            }
        });
    }
    
    /**
     * DELETE请求
     */
    public void delete(String endpoint, ApiCallback callback) {
        executorService.execute(() -> {
            try {
                String url = BASE_URL + endpoint;
                Log.d(TAG, "DELETE请求: " + url);
                
                HttpURLConnection connection = createConnection(url, "DELETE");
                connection.connect();
                
                int responseCode = connection.getResponseCode();
                String response = readResponse(connection);
                
                if (responseCode >= 200 && responseCode < 300) {
                    Log.d(TAG, "DELETE请求成功: " + responseCode);
                    callback.onSuccess(response);
                } else {
                    Log.e(TAG, "DELETE请求失败: " + responseCode + ", " + response);
                    callback.onError("请求失败: " + responseCode + " - " + response);
                }
                
                connection.disconnect();
                
            } catch (Exception e) {
                Log.e(TAG, "DELETE请求异常", e);
                callback.onError("请求异常: " + e.getMessage());
            }
        });
    }
    
    /**
     * 创建HTTP连接
     */
    private HttpURLConnection createConnection(String urlString, String method) throws IOException {
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        
        connection.setRequestMethod(method);
        connection.setConnectTimeout(CONNECT_TIMEOUT);
        connection.setReadTimeout(READ_TIMEOUT);
        connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        connection.setRequestProperty("Accept", "application/json; charset=UTF-8");
        connection.setRequestProperty("Accept-Charset", "UTF-8");
        
        // 添加认证头（如果需要）
        // connection.setRequestProperty("Authorization", "Bearer " + token);
        
        return connection;
    }
    
    /**
     * 读取响应
     */
    private String readResponse(HttpURLConnection connection) throws IOException {
        BufferedReader reader;
        
        if (connection.getResponseCode() >= 200 && connection.getResponseCode() < 300) {
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
        } else {
            reader = new BufferedReader(new InputStreamReader(connection.getErrorStream(), StandardCharsets.UTF_8));
        }
        
        StringBuilder response = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();
        
        return response.toString();
    }
    
    /**
     * 检查网络连接
     */
    public boolean isNetworkAvailable() {
        try {
            // 简单的网络检查
            URL url = new URL(BASE_URL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            connection.setRequestMethod("GET");
            
            int responseCode = connection.getResponseCode();
            connection.disconnect();
            
            return responseCode >= 200 && responseCode < 300;
        } catch (Exception e) {
            Log.e(TAG, "网络检查失败", e);
            return false;
        }
    }
    
    /**
     * 关闭线程池
     */
    public void shutdown() {
        if (executorService != null && !executorService.isShutdown()) {
            executorService.shutdown();
        }
    }
    
    /**
     * 设置基础URL
     */
    public static void setBaseUrl(String baseUrl) {
        // 这里可以添加设置基础URL的逻辑
        Log.d(TAG, "设置基础URL: " + baseUrl);
    }
    
    /**
     * 获取基础URL
     */
    public static String getBaseUrl() {
        return BASE_URL;
    }
}